package pt.mauromad.guias.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {
	public static enum Format {
		DATE_TIME("yyyy-MM-dd HH:mm"), DATE("yyyy-MM-dd");

		private final String format;

		private Format(String format) {
			this.format = format;
		}

		public DateFormat getFormatter() {
			return new SimpleDateFormat(format);
		}

		@Override
		public String toString() {
			return String.format("Format[%s]", format);
		}
	}

	public static String convertDate(Date date) {
		return convert(date, Format.DATE);
	}

	public static Date convertDate(String date) {
		return convert(date, Format.DATE);
	}

	public static String convertDateTime(Date date) {
		return convert(date, Format.DATE_TIME);
	}

	public static Date convertDateTime(String date) {
		return convert(date, Format.DATE_TIME);
	}

	public static Object tryConvertDateToStr(Object o) {
		if (o instanceof Date)
			return convertDateTime((Date) o);

		return o;
	}

	public static Object tryConvertDateTimeToStr(Object o) {
		if (o instanceof Date)
			return convertDateTime((Date) o);

		return o;
	}

	private static Date convert(String date, Format format) {
		if (date == null)
			return null;

		try {
			return format.getFormatter().parse(date);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

	private static String convert(Date date, Format format) {
		if (date == null)
			return null;

		return format.getFormatter().format(date);
	}

	public static Date fromString(String text) {
		if (text == null || text.length() == 0)
			return null;

		for (Format f : Format.values())
			try {
				return f.getFormatter().parse(text);
			} catch (Exception e) {
				// Do nothing
			}
		return null;
	}
}
